
package com.buddies.lottery.widget;

import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;


/**
 * 个人中心页 space
 */
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpace;

    public SpaceItemDecoration(int space) {
        mSpace = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        int pos = parent.getChildAdapterPosition(view);

        GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
        GridLayoutManager.SpanSizeLookup spanSizeLookup = layoutManager.getSpanSizeLookup();
        boolean isHeader = spanSizeLookup.getSpanSize(pos) != 1;

        if (isHeader) {
            outRect.set(0, 0, 0, 0);
        } else {
            int itemCount = parent.getAdapter().getItemCount();
            if (itemCount == 0) {
                outRect.set(0, 0, 0, 0);
            } else {
                int spanCount = layoutManager.getSpanCount();
                int indexOfRow = spanSizeLookup.getSpanIndex(pos, spanCount);

                boolean hasHeader = spanSizeLookup.getSpanSize(0) != 1;
                if (hasHeader) { // 有header，重新计算itemCount，精准判断是否添加bottom
                    itemCount += spanCount - 1;
                }

                int bottom = 0;
                int childPosition = parent.getChildAdapterPosition(view);
                if (childPosition + spanCount - indexOfRow >= itemCount) {// 最后一行添加bottom
                    bottom = mSpace;
                }

                if (spanCount > 1) {
                    if (indexOfRow == 0) {// 第一个
                        outRect.set(mSpace, mSpace, mSpace / 2, bottom);
                    } else if (indexOfRow == spanCount - 1) { // 最后一个
                        outRect.set(mSpace / 2, mSpace, mSpace, bottom);
                    } else { // 中间的
                        outRect.set(mSpace / 2, mSpace, mSpace / 2, bottom);
                    }
                } else {
                    outRect.set(mSpace, mSpace, mSpace, bottom);
                }
            }

        }
    }
}